'''
Created on Jul 20, 2012

@author: LENOVO
'''
import re

class NumberExtractor(object):
    '''
    Takes a string that represents a number and transforms it into its decimal 
    representation; i.e. 'three hundred and twenty one', is 321.  
    '''
    
    STRING_TO_NUM = { 'one':1,
                    'two':2,
                    'three':3,
                    'four':4,
                    'five':5,
                    'six':6,
                    'seven':7,
                    'eight':8,
                    'nine':9,
                    'ten':10,
                    'eleven':11,
                    'twelve':12,
                    'thirteen':13,
                    'fourteen':14,
                    'fifteen':15,
                    'sixteen':16,
                    'seventeen':17,
                    'eighteen':18,
                    'nineteen':19,
                    'twenty':20,
                    'thirty':30,
                    'forty':40,
                    'fifty':50,
                    'sixty':60,
                    'seventy':70,
                    'eighty':80,
                    'ninety':90,
                    'hundred':100,
                    'thousand':1000,
                    'million':1000000}

    def __init__(self):
        '''
        Assuming the following format of the number:
        ([word digit][positional value]|[word digit])+
        '''
        self.number = 0
    
    def getNumber(self,numberString):
        digitStack = []
        
        # break string into words separated by ' ' and punctuation marks
        wordDigits = re.split('\W+',numberString,flags = re.IGNORECASE)
        
        # calculating the number
        for wordDigit in wordDigits:
            digit = NumberExtractor.STRING_TO_NUM.get(wordDigit)
            if digit is None:
                pass
            else:
                # of the form [word digit][positional value]
                if (len(digitStack) == 1) and (digit > digitStack[0]):
                    self.number += digitStack[0]*digit
                    digitStack = []
                # of the form [word digit]
                elif (len(digitStack) == 1) and (digit < digitStack[0]):
                    self.number += (digit+digitStack[0])
                    digitStack = []
                # just entered a number to the stack
                else:
                    digitStack += [digit]
        return self.number